package cn.edu.gzgs.mapper;

import cn.edu.gzgs.entity.LoginLog;
import com.baomidou.mybatisplus.core.mapper.BaseMapper;
import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;

import java.time.LocalDateTime;

@Mapper
public interface LoginLogMapper extends BaseMapper<LoginLog> {

    /**
     * 查询指定用户/IP在特定时间窗口内登录失败的次数
     * @param userNo 工号
     * @param ipAddress IP地址
     * @param startTime 开始时间
     * @param endTime 结束时间
     * @return 失败次数
     */
    @Select("SELECT COUNT(*) FROM login_log " +
            "WHERE (username_or_user_no = #{userNo} OR ip_address = #{ipAddress}) " +
            "AND login_status != 'SUCCESS' " +
            "AND attempt_time BETWEEN #{startTime} AND #{endTime}")
    int countFailedAttemptsInWindow(@Param("userNo") String userNo,
                                    @Param("ipAddress") String ipAddress,
                                    @Param("startTime") LocalDateTime startTime,
                                    @Param("endTime") LocalDateTime endTime);

    /**
     * 查询用户上一次成功登录的IP地址
     * @param userId 用户ID
     * @return 上一次成功登录的IP，如果没有则返回null
     */
    @Select("SELECT ip_address FROM login_log " +
            "WHERE user_id = #{userId} AND login_status = 'SUCCESS' " +
            "ORDER BY attempt_time DESC LIMIT 1")
    String findLastSuccessfulLoginIp(@Param("userId") Long userId);

} 